package com.pureman.androidapp;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;

import com.pureman.androidapp.network.NetWorkUtil;
import com.pureman.androidapp.utils.LogUtils;

import java.util.List;

/**
 * 窗口布局基类
 *
 * @author yuanyugen
 */
public class BaseActivity extends Activity {

    public MainApplication application;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        application = (MainApplication) getApplication();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if (!isAppOnForeground() && MainApplication.isActive) {
            //app 进入后台,记录当前已经进入后台
            MainApplication.isActive = false;
            LogUtils.i("BaseActivity-->进入后台,记录当前已经进入后台");
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (!MainApplication.isActive) {
//          app 从后台唤醒，进入前台
            MainApplication.isActive = true;
            LogUtils.i("BaseActivity-->从后台唤醒，进入前台");
            if (NetWorkUtil.getNetworkState(BaseActivity.this) != NetWorkUtil.NETWORN_NONE) {
            }
        }
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }
}
